import { Injectable } from '@angular/core';
import { Http, Headers } from "@angular/http";
import { TurboperCurrentTotle } from "../entity/turboper-current-totle.model";
import { Observable } from "rxjs/Rx";
import { AppConfig } from "../config";
import {TurboperCurrent} from "../entity/turboper-current.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class TurboperCurrentService {
    private param = "operCurrents";
    private get url(): string {
        //return `http://192.168.15.3:8585/webapi/v1/${this.param}`
        return `${AppConfig.APP_RESTFUL}/${this.param}`;
    }

    constructor(private http: InterceptorService) {

    }

    getTurboperCurrentTotle(): Promise<TurboperCurrentTotle[]> {
        let url = `${this.url}/homePage/farmTurOper`;
        return this.http.get(url).toPromise()
            .then(res => res.json().data as TurboperCurrentTotle[])
            .catch(this.handleError);
    }
    private handleError(error: any): Promise<any> {
        return Promise.reject(error.message || error);
    }
    create(turboperCurrent: TurboperCurrent): Promise<TurboperCurrent> {
        //let url = `http://192.168.15.150:8585/webapi/v1/operCurrents`
        return this.http.post(this.url, JSON.stringify(turboperCurrent))
            .toPromise()
            .then(res => {
                try {
                    let result = res.json();
                    switch (result.code) {
                        case "200":
                            return result.data as TurboperCurrent;
                        case "-1":
                            throw new Error(result.message);
                    }
                }
                catch (error) {
                    this.handleError(error);
                }
            })
            .catch(this.handleError);
    }
    update(farm: TurboperCurrent): Promise<TurboperCurrent> {
        // let url=`http://192.168.15.150:8585/webapi/v1/operCurrents`
        return this.http.put(this.url, JSON.stringify(farm))
          .toPromise()
          .then(() => farm)
          .catch(this.handleError);
      }
    delete(id: number): Promise<void> {
        const url = `${this.url}/${id}`;
        return this.http.delete(url)
            .toPromise()
            .then(() => null)
            .catch(this.handleError);

    }
    getOperCurrentsBydeviceId(deviceId:number):Promise<TurboperCurrent[]>{
        const url = `${this.url}/deviceId/${deviceId}`;
        return this.http.get(url).toPromise()
        .then(res => res.json().data as TurboperCurrent[])
        .catch(this.handleError);
    }

}



// WEBPACK FOOTER //
// ./src/app/service/turboper_current.service.ts